package com.qiqi.mealordersystem.Service;

import com.alibaba.fastjson.JSON;
import com.qiqi.mealordersystem.Mapper.SystemUserMapper;
import com.qiqi.mealordersystem.model.SystemUser;
import com.qiqi.mealordersystem.model.vo.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SystemUserService{

    private SystemUserMapper mapper;

    @Autowired
    public SystemUserService(SystemUserMapper mapper) {
        this.mapper = mapper;
    }

    public String addUser(String userString){

        String result;

        SystemUser user = JSON.parseObject(userString, SystemUser.class);
        SystemUser systemUser = mapper.selectSystemUser(user);
        if (systemUser != null){
            result="该用户已存在";
        }else {
            Integer userid = mapper.insertSystemUser(user);
            result="添加成功，工号为"+userid;
        }

        return result;

    }


    public String deleteUser(String userString){
        String result;
        List<SystemUser> systemUserList = JSON.parseArray(userString, SystemUser.class);

        List<SystemUser> failed = new ArrayList<>();
        List<SystemUser> success = new ArrayList<>();

        for(SystemUser user:systemUserList){
            SystemUser systemUser = mapper.selectSystemUser(user);
            if(systemUser != null){
                success.add(systemUser);
            }else{
                failed.add(user);
            }
        }
        if (success.size()>0)
            mapper.deleteSystemUser(success);
        result="删除成功"+JSON.toJSONString(success)+"删除失败"+JSON.toJSONString(failed);
        return result;
    }

    public String updateUser(String userString){
        String result;

        SystemUser systemUser = selectUser(userString);
        if(systemUser != null){
            Integer integer = mapper.updateSystemUser(systemUser);
            result = "修改成功"+integer;
        }
        else{
            result = "用户不存在，修改失败";
        }

        return result;

    }

    public SystemUser selectUser(String userString){

        String result;
        SystemUser user = JSON.parseObject(userString, SystemUser.class);
        SystemUser systemUser = mapper.selectSystemUser(user);
        return systemUser;

    }

    public String ShowUserDtail(String userString){

        SystemUser systemUser = selectUser(userString);
        UserDetail userDetail = new UserDetail();
        userDetail.setUserid(systemUser.getUserid());
        userDetail.setUsername(systemUser.getUsername());
        userDetail.setBirthday(systemUser.getBirthday());
        userDetail.setEmail(systemUser.getEmail());
        userDetail.setPhone(systemUser.getPhone());
        userDetail.setSex(systemUser.getSex());
        userDetail.setAdmin(systemUser.getAdmin());

        return JSON.toJSONString(userDetail);
    }

}
